import { Button } from 'antd';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { useCallback, useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import FilterItemTagList from '../components/filter/FilterItemTagList';
import { getTitlebyPathname } from '../libs/filterCommon';
import useFilterMeta from '../libs/hooks/useFilterMeta';
import useFilterMetaCSC from '../libs/hooks/useFilterMetaCSC';
import useFilterPopupWindow from '../libs/hooks/useFilterPopupWindow';
import useSaveFilter from '../libs/hooks/useSaveFilter';
import useUserInfo from '../libs/hooks/useUserInfo';
import { chartAction } from '../libs/slices/chartManagerSlice';
import { filterAction, filterState } from '../libs/slices/filterSlice';
const ChartEditModal = dynamic(() => import('../components/ChartEditModal'));
const CatalogFilter = dynamic(() => import('../components/filter/CatalogFilter'));
const DateRangePopup = dynamic(() => import('../components/filter/DateRangePopup'));
const DimensionFilterPopup = dynamic(
  () => import('../components/filter/DimensionFilterPopup'),
);
const FilterEditPopup = dynamic(() => import('../components/filter/FilterEditPopup'));
const FilterTemplate = dynamic(() => import('../components/templates/FilterTemplate'));
const SavedFilterList = dynamic(() => import('../components/filter/SavedFilterList'));
const NoneSelectedWarning = dynamic(
  () => import('../components/filter/NoneSelectedWarning'),
);

export default function Filters() {
  const { filterMeta, isLoading, catalog, updateCatalog } = useFilterMeta();
  const { filerMetaCSC,updateCatalogCSC} = useFilterMetaCSC();
  const { selectedFilter } = useSelector(filterState);
  const { userDefaultFilter } = useUserInfo();
  const { setSavedFilterId } = useSaveFilter();
  const dispatch = useDispatch();
  const route = useRouter().route;
  const { popupActive, togglePopupActive, globalFilterConfig } = useFilterPopupWindow();

  useEffect(() => {
    if (userDefaultFilter) {
      updateCatalog(userDefaultFilter.productType);
      updateCatalogCSC(userDefaultFilter.productType);
      setSavedFilterId(userDefaultFilter.savedFilterId);

      dispatch(
        filterAction.setFilter({
          filter: userDefaultFilter,
          productType: userDefaultFilter.productType,
        }),
      );
      dispatch(filterAction.setPeriod(userDefaultFilter.date));
    }
  }, [userDefaultFilter]);

  const selectedDimensionFilters: { [k: string]: string[] } = {
    // location: catalog=="wearable"?['CN']:selectedFilter.location,
    location: selectedFilter.location,
    device: selectedFilter.device,
  };

  const pageTitle = getTitlebyPathname(route);

  const onClick = () => togglePopupActive('dimension', popupActive.dimension);

  const disables = useMemo(() => {
    return Object.keys(selectedDimensionFilters).filter(
      filterKey => selectedDimensionFilters[filterKey].length === 0,
    );
  }, [selectedDimensionFilters]);

  const disabledFilters = globalFilterConfig?.disabledFilters[catalog];

  const selectedFilterTags = (
    <div style={{ display: 'inline-block' }} onClick={onClick}>
      {disables.length > 0 && (
        <NoneSelectedWarning items={disables} display="inline-flex" />
      )}
      <>
        {Object.keys(selectedDimensionFilters).map(
          (filterKey, i) =>
            !disabledFilters?.includes(filterKey) &&
            selectedDimensionFilters[filterKey]?.length > 0 && (
              <FilterItemTagList
                key={i}
                filterKey={filterKey}
                items={selectedDimensionFilters[filterKey]}
              />
            ),
        )}
      </>
    </div>
  );

  const onClickChartEditButton = useCallback(() => {
    dispatch(chartAction.toggleModalVisible());
  }, [chartAction]);

  const chartEditButton = pageTitle === 'Dashboard' && (
    <Button size="small" onClick={onClickChartEditButton} shape="round">
      Edit
    </Button>
  );

  return (
    <FilterTemplate
      globalFilterConfig={globalFilterConfig}
      catalogFilter={<CatalogFilter />}
      savedFilterPopup={<SavedFilterList />}
      selectedFilterTags={selectedFilterTags}
      pageTitle={pageTitle}
      chartEditButton={chartEditButton}
      dimensionFilterPopup={
        <DimensionFilterPopup
          selectedFilters={selectedDimensionFilters}
          loading={isLoading}
          treeData={filterMeta}
          treeDataCSC={filerMetaCSC}
        />
      }
      dateRangePopup={<DateRangePopup />}
      filterEditPopup={<FilterEditPopup />}
      chartEditModal={<ChartEditModal />}
    />
  );
}
